package com.test.tool.demo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * socket握手拦截器,主要用于用户验证
 *
 * @author 小八
 * @date 2022年04月25日15:16
 */
@Slf4j
public class EhomeHandshakeInterceptor implements HandshakeInterceptor {


    /**
     * websocket 握手之前
     *
     * @param serverHttpRequest  request
     * @param serverHttpResponse response
     * @param webSocketHandler   处理器
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        ServletServerHttpRequest req = (ServletServerHttpRequest) serverHttpRequest;
//        WebSocketUser user = null;
//        //获取token认证
//        String token = req.getServletRequest().getParameter("token");
        //解析token获取用户信息
        //鉴权，前端把token传过来，解析token，判断正确与否，return true表示通过，false请求不通过。
        //TODO 鉴权设置用户
//        if (StrUtil.isNotBlank(token)) {
//            user = new WebSocketUser(token);
//        }
//
//        //如果token认证失败user为null，返回false拒绝握手
//        if (user == null) {
//            return false;
//        }
//        //保存认证用户
//        map.put("user", user);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }

}
